import React from 'react'
import { View, StyleSheet, DeviceEventEmitter } from 'react-native'
import { connect } from 'react-redux'
import BasePage from 'src/pageP/base/base-page/index'
import { ONE_PIXEL, ScaleS } from '../../../utils/ScreenUtil'
import CustomButton from '../../../components/button/CustomButton'
import SearchHeader from './components/SearchHeader'
import SearchHistory from './components/SearchHistory'
import CustomFlatList from '../../../components/custom-flat-list/index'
import { homePostList, queryArchive } from '../../../utils/RequestAPI'
import PersonCell from '../../../components/person-cell/index'
import JobCell from '../../../components/job-cell/index'
import RefreshState from 'src/components/custom-flat-list/RefreshState'
import EmptyView from '../../../components/empty-view/index'
import DeviceStorage from '../../../utils/DeviceStorage'
import NavigationUtil from '../../../utils/NavigationUtil'
import { DismissLoading, ShowLoading } from 'src/utils/ToastUtil'
import { RNTPolyvLivePlayerView, RNTPolyvLiveView } from 'src/bridge'

const CITY = 'city'
const NAME = 'name'
const SEARCH_HISTORY = 'searchHistory'
const HISTORY_ARR = 'historyArr'
const requestParamC = {
  page: 'page',
  limit: 'limit',
  [CITY]: 'city',
  [NAME]: 'name',
  [SEARCH_HISTORY]: 'searchHistoryC'
}
const requestParamB = {
  page: 'page',
  limit: 'limit',
  [CITY]: 'jobPlace',
  [NAME]: 'query',
  [SEARCH_HISTORY]: 'searchHistoryB'
}
// 发送行为
const mapDispatchToProps = dispatch => ({})

@connect(({ landmark, userinfo }) => ({
  landmark,
  isPageB: userinfo.role === 'B',
  userinfo
}), mapDispatchToProps)
class HomeSearch extends BasePage {
  constructor (props) {
    super(props)
    const { navigation: { state: { params: { type } = {} } }, userinfo: { userId = '' } } = this.props
    this.type = type
    this.state = {
      header: {},
      historyArr: [],
      dataArr: [],
      showHistory: true,
      text: ''
    }
    this.isPageB = props.isPageB
    this.requestParams = {
      page: 1,
      limit: 10,
      [this._getRequestKey(CITY)]: props.landmark.cityName,
      userId
    }
    this.deviceStoryKey = this._getRequestKey(SEARCH_HISTORY)
  }

  _getRequestKey = (key) => {
    return this.isPageB ? requestParamB[key] : requestParamC[key]
  }

  childRender () {
    const { landmark } = this.props
    const { historyArr, dataArr, showHistory, text } = this.state
    return (
      <View style={styles.container}>
        <SearchHeader
          ref={this._searchHeaderRef}
          landmark={landmark}
          cityCallback={this._cityCallback}
          clearInput={this._clearInput}
          text={text}
          isPageB={this.isPageB}
          onSubmitEditing={this._onSubmitEditing}/>
        {/* <View style={styles.horizontalLine} /> */}
        {
          showHistory ? (
            <SearchHistory
              deleteClick={this._deleteClick}
              historyArr={historyArr}
              itemClick={this._historyItemClick}/>) : (
            <CustomFlatList
              style={styles.flatListView}
              ref={this._flatListRef}
              pullDown={false}
              keyExtractor={this._keyExtractor}
              data={dataArr}
              renderItem={this._renderItem}
              onHeaderRefresh={this._onHeaderRefresh}
              onFooterRefresh={this._onFooterRefresh}
              ListEmptyComponent={this._ListEmptyComponent()}
            />
          )
        }
      </View>
    )
  }

  componentDidMount () {
    // todo 获取搜索历史
    DeviceStorage.get(this.deviceStoryKey).then((data) => {
      console.info(data)
      if (data[HISTORY_ARR]) {
        this.setState({
          historyArr: data[HISTORY_ARR]
        })
      }
    })
  }

  _searchHeaderRef = (ref) => {
    this._searchHear = ref
  }

  _clearInput = () => {
    this.setState({
      showHistory: true,
      text: '',
      dataArr: []
    })
  }

  _onSubmitEditing = (text) => {
    const { historyArr } = this.state
    this.requestParams[this._getRequestKey(NAME)] = text
    const newHistoryArr = historyArr.reduce((total, item) => {
      if (item.label !== text) total.push(item)
      return total
    }, [
      { label: text }
    ])
    this.setState({
      showHistory: false,
      text,
      historyArr: newHistoryArr
    }, () => {
      this._onHeaderRefresh()
      // todo 存储搜索历史，并且更新到historyArr
      DeviceStorage.set(this.deviceStoryKey, {
        [HISTORY_ARR]: newHistoryArr
      })
    })
  }

  _ListEmptyComponent = () => {
    return (
      <EmptyView emptyImg={require('src/imgC/home/home_no_data.png')} firstTip={'暂无相关数据'}/>
    )
  }

  _keyExtractor = (item) => {
    return item.id.toString()
  }

  _flatListRef = (ref) => {
    this.customFlatList = ref
    console.info('this.customFlatList', this.customFlatList)
  }

  _renderItem = ({ item }) => {
    const { landmark } = this.props
    return (
      <CustomButton params={item} onPress={this._itemOnPress}>
        {
          this.isPageB ? (
            <PersonCell item={item}/>
          ) : (
            <JobCell landmark={landmark} item={item}/>
          )
        }
      </CustomButton>
    )
  }

  /**
   * 每一条点击的事件
   * @private
   */
  _itemOnPress = (item) => {
    this.isPageB ? this._personClick(item) : this._jobClick(item)
  }

  _personClick = (item) => {
    NavigationUtil.navigate('CResumeDetail', {
      userId: item.userId,
      type: this.type
    })
  }

  _jobClick = (item) => {
    NavigationUtil.navigate('CJobdetail', {
      id: item.id
    })
  }

  /**
   * 城市选择的回调
   * @param cityName
   * @private
   */
  _cityCallback = (cityName) => {
    if (this.requestParams[this._getRequestKey(CITY)] !== cityName) {
      this.requestParams[this._getRequestKey(CITY)] = cityName
      console.info(this._searchHear)
      if (this._searchHear.state.text) {
        this.setState({
          showHistory: false
        }, () => {
          this._onHeaderRefresh()
        })
      }
    }
  }

  /**
   * 历史记录的点击
   * @param label
   * @private
   */
  _historyItemClick = ({ label }) => {
    this._onSubmitEditing(label)
  }

  /**
   * 删除历史记录
   * @private
   */
  _deleteClick = () => {
    const { historyArr } = this.state
    if (historyArr.length > 0) {
      DeviceStorage.delete(this.deviceStoryKey).then(() => {
        this.setState({
          historyArr: []
        })
      })
    }
  }

  /**
   * 下拉刷新
   * @private
   */
  _onHeaderRefresh = () => {
    this.requestParams.page = 1
    this._searchRequest(true).then((data) => {
      this._setStateData(data, data)
    })
  }

  /**
   * 搜索请求
   * @private
   */
  _searchRequest = async (showLoading) => {
    showLoading && ShowLoading()
    const params = { params: this.requestParams }
    let result = {}
    if (this.isPageB) {
      result = await queryArchive(params)
    } else {
      result = await homePostList(params)
    }
    console.info(result)
    showLoading && DismissLoading()
    return result.data
  }

  /**
   * 设置搜索数据
   * @param originData
   * @param dataArr
   * @private
   */
  _setStateData = (originData, dataArr) => {
    const setEndRefreshingState = () => {
      const setEndRefreshState = (state) => {
        this.customFlatList.endRefreshing(state)
      }
      if (originData && originData.length > 9) {
        setEndRefreshState(RefreshState.CanLoadMore)
      } else {
        setEndRefreshState(RefreshState.NoMoreData)
      }
    }
    this.setState({ dataArr: dataArr }, () => {
      setEndRefreshingState()
    })
  }

  /**
   * 上拉加载
   * @private
   */
  _onFooterRefresh = () => {
    const { dataArr } = this.state
    this.requestParams.page++
    this._searchRequest().then((data) => {
      this._setStateData(data, dataArr.concat(data))
    })
  }
}

export default HomeSearch

const styles = StyleSheet.create({
  container: {
    flex: 1,
    paddingLeft: ScaleS(18.5),
    paddingRight: ScaleS(18.5)
  },
  horizontalLine: {
    height: ONE_PIXEL,
    backgroundColor: '#EFEFEF',
    marginTop: ScaleS(20)
  }
})
